<template>
  <div class="increaseArticleOuter">
    <div class="increaseArticle">
      <el-scrollbar height="86vh">
        <!-- 文章标题 -->
        <el-row justify="start">
          <el-col class="title" :span="2"> 文章标题： </el-col>
          <el-col :span="21" :offset="0">
            <el-input placeholder="请输入标题" v-model="articleInfo.title" clearable />
          </el-col>
        </el-row>

        <!-- 文章简介 -->
        <el-row justify="start">
          <el-col class="title" :span="2"> 文章简介： </el-col>
          <el-col :span="21" :offset="0">
            <el-input :rows="2" type="textarea" v-model="articleInfo.synopsis" placeholder="请输入简介" />
          </el-col>
        </el-row>

        <!-- 文章封面 -->
        <el-row justify="start">
          <el-col class="title" :span="2"> 文章封面： </el-col>
          <el-col :span="4" :offset="0">
            <div class="imgUpOuter">
              <el-col :span="24">
                <el-row style="margin: 10px 0">
                  <el-upload class="avatar-uploader" style="height: 80px" list-type="picture-card" action
                    :http-request="uploadFile" ref="upload" :file-list="fileList" :show-file-list="false"
                    :headers="headers">
                    <template #default style="height: 80px">
                      <img v-if="imageUrl" @click.stop="" :src="imageUrl" class="avatar" />
                      <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                      </el-icon>
                    </template>
                  </el-upload>
                </el-row>
                <el-row>
                  <el-col :span="12" style="display: flex;
                      align-items: center;
                      justify-content: center;
                    ">
                    <el-button type="danger" size="small" round @click="delImg">
                      删除
                    </el-button>
                  </el-col>
                </el-row>
              </el-col>
            </div>
          </el-col>
          <el-col :span="10">
            <!-- 标签 -->
            <el-row>
              <el-col class="tag" :span="3">贴个标签</el-col>
              <el-col :span="20">
                <el-select class="m-2" v-model="articleInfo.tag" placeholder="请选择">
                  <el-option v-for="item in options1" :key="item._id" :label="item.tagName" :value="item.tagName" />
                </el-select>
              </el-col>
            </el-row>
            <!-- 分类 -->
            <el-row>
              <el-col class="tag" :span="3">选择分类</el-col>
              <el-col :span="20">
                <el-select class="m-2" v-model="articleInfo.category" placeholder="请选择">
                  <el-option v-for="item in options" :key="item._id" :label="item.categoryName"
                    :value="item.categoryName" />
                </el-select>
              </el-col>
            </el-row>
          </el-col>
        </el-row>

        <!-- 富文本编辑器 -->
        <el-row class="richTextEditor">
          <RichTextEditor @articleText="receive" :id="route.query.id?route.query.id as string:'null'" />
        </el-row>

        <el-row>
          <el-col :span="6" :offset="3">
            <el-button type="warning" round @click="draft">保存草稿</el-button>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" round @click="release">发布文章</el-button>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" round @click="clear">重置</el-button>
          </el-col>
        </el-row>
      </el-scrollbar>
    </div>
  </div>
</template>

<script setup lang="ts">
import RichTextEditor from "../../components/RichTextEditor.vue";

// 上传
import { ref, reactive, toRefs, onMounted } from "vue";
import { useRoute } from 'vue-router'
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import axios from "../../service/request";
import { findImgApi, delImgApi } from "../../service/apiModule/bgImgApi";
import { addArticleApi, getArticleApi, upArticleApi } from '../../service/apiModule/articleApi'
import { getCategoryApi } from '../../service/apiModule/categoryApi'
import {
  getTagApi,
} from "../../service/apiModule/tagApi";
import { AnyFn } from "@vueuse/shared";

const route = useRoute()

onMounted(() => {
  getCategory()
  if (route.query.id) {
    getArticle({ id: route.query.id })
  }

  getTag()
});

let imageUrl = ref("");
imageUrl.value = ''

// 请求头
const headers = reactive({ "Content-Type": "multipart/form-data" });
//上传后的文件列表
const fileList: any = [];

// 获取封面
const getBgImg = async () => {
  const { data: res } = await findImgApi();
  console.log(res)
  res.data.forEach((item: any) => {
    if (item.bgTitle === `${articleInfo.title}封面`) {
      imageUrl.value = item.imgSrc;
      articleInfo.cover = item.imgSrc
    }
  });
};

// 获取分类
const getCategory = async () => {
  const { data: res } = await getCategoryApi({ categoryName: "" })
  options.value = res.data.list
}

// 标签
const options1 = ref([
  {
    tagName: "",
    _id: ""
  }
]);

// 分类
const options = ref([
  {
    categoryName: "",
    _id: ""
  }
]);

// 获取标签数据
const getTag = async () => {
  const { data: res } = await getTagApi({ name: "" });
  if (res.status.code !== 200) {
    ElMessage.error("标签获取失败!");
  } else {
    const arr: any = []

    res.data.list.forEach((item: any) => {
      if (item.tagStatus === true) {
        arr.push(item)
      }
    })

    options1.value = arr
  }
};

// 获取文章信息
const getArticle = async (info?: any) => {
  const { data: res } = await getArticleApi(info)
  if (res.status.code !== 200) {
    ElMessage.error('文章信息获取失败!')
  } else {
    articleInfo.title = res.data.title
    articleInfo.synopsis = res.data.introduction
    getBgImg()
    articleInfo.tag = res.data.tag
    articleInfo.category = res.data.category
  }
}

// 上传
const uploadFile = async (item: any) => {
  //上传文件的需要formdata类型;所以要转
  let formData = new FormData();
  // formData. append (name, value, filename);
  formData.append("file", item.file, `${articleInfo.title}封面.jpg`);
  axios({
    url: "/manage/upImg",
    method: "POST",
    timeout: 6000,
    data: formData,
    headers: {
      "content-type": "multipart/form-data",
    },
  })
    .then((res: any) => {
      ElMessage.success("上传成功！");
      getBgImg();
    })
    .catch((err: any) => {
      ElMessage.error("上传失败!");
    });
};

// 删除图片
const delImg = async () => {
  imageUrl.value = "";
  const { data: res } = await delImgApi({ bgTitle: "文章封面" });
  if (res.status.code !== 200) {
    ElMessage.error("删除失败!");
  } else {
    ElMessage.success("删除成功!");
  }
};

// 文章信息
const articleInfo = reactive({
  title: "", // 标题
  synopsis: "", // 简介
  cover: "", // 封面
  tag: "", // 标签
  category: "", // 分类
  content: "", // 文章内容
});

const clearInfo = () => {
  articleInfo.title = ""
  articleInfo.synopsis = ""
  articleInfo.tag = ""
  articleInfo.category = ""
  articleInfo.content = ""
}

// 文本内容
const receive = (data: any) => {
  articleInfo.content = data
};

// 草稿
const draft = async () => {
  if (route.query.id) {
    // 修改
    const { data: res } = await upArticleApi({
      id: route.query.id,
      title: articleInfo.title,
      introduction: articleInfo.synopsis,
      articleCover: articleInfo.cover,
      category: articleInfo.category,
      tag: articleInfo.tag,
      commentLikeFavorites: '0/0/0',
      articleStatus: '草稿',
      articleContent: articleInfo.content
    })
    if (res.status.code === 200) {
      ElMessage.success('草稿保存成功!')
    } else {
      ElMessage.error('草稿保存失败!')
      console.log(res)
    }
  } else {
    if (articleInfo.title !== '') {
      if (articleInfo.synopsis !== '') {
        const { data: res } = await addArticleApi({
          title: articleInfo.title,
          introduction: articleInfo.synopsis,
          articleCover: articleInfo.cover,
          category: articleInfo.category,
          tag: articleInfo.tag,
          commentLikeFavorites: '0/0/0',
          articleStatus: '草稿',
          articleContent: articleInfo.content
        })
        if (res.status.code === 200) {
          ElMessage.success('草稿保存成功!')
        } else {
          ElMessage.error('草稿保存失败!')
        }
      } else {
        ElMessage.info('简介不可为空!')
      }
    } else {
      ElMessage.info('标题不可为空!')
    }
  }
}

// 发布
const release = async () => {
  if (route.query.id) {
    const { data: res } = await upArticleApi({
      id: route.query.id,
      title: articleInfo.title,
      introduction: articleInfo.synopsis,
      articleCover: articleInfo.cover,
      category: articleInfo.category,
      tag: articleInfo.tag,
      commentLikeFavorites: '0/0/0',
      articleStatus: '已发布',
      articleContent: articleInfo.content
    })
    if (res.status.code === 200) {
      ElMessage.success('文章发布成功!')
    } else {
      ElMessage.error('文章发布失败!')
    }
  } else {
    if (articleInfo.title !== '') {
      if (articleInfo.synopsis !== '') {
        const { data: res } = await addArticleApi({
          title: articleInfo.title,
          introduction: articleInfo.synopsis,
          articleCover: articleInfo.cover,
          category: articleInfo.category,
          tag: articleInfo.tag,
          commentLikeFavorites: '0/0/0',
          articleStatus: '已发布',
          articleContent: articleInfo.content
        })
        if (res.status.code === 200) {
          ElMessage.success('文章发布成功!')
        } else {
          ElMessage.error('文章发布失败!')
        }
      } else {
        ElMessage.info('简介不可为空!')
      }
    } else {
      ElMessage.info('标题不可为空!')
    }
  }

}

// 重置
const clear = () => {
  clearInfo()
}
</script>

<style lang="scss" scoped>
.increaseArticleOuter {
  width: 100%;
  height: 91vh;
  padding: 10px 0 0px 20px;
  overflow: hidden;
  background-color: rgba(230, 230, 230, 0.6);

  .increaseArticle {
    width: 99%;
    height: 100%;
    border: 1px solid orange;
    background-color: #fff;
    border-radius: 20px 20px 0 0;
    padding: 16px 0 0 20px;

    .el-row {
      display: flex;
      align-items: center;

      &:not(:last-child) {
        margin-bottom: 20px;
      }

      &>.title {
        font-size: 18px;
        font-family: "楷体";
        font-weight: bold;
      }

      .el-col {
        .tag {
          font-family: "楷体";
          font-weight: bold;
          font-size: 14px;
        }

        // 文章封面
      }
    }

    .switchOuter {
      font-size: 14px;
      font-weight: bold;
      font-family: "楷体";
    }

    .richTextEditor {
      width: 99%;
    }
  }

  .imgUpOuter {
    margin-left: 40px;

    .avatar {
      width: 80px;
      height: 80px;
    }

    .avatar-uploader {
      width: 80px;
      height: 80px;
      display: block;
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      transition: var(--el-transition-duration-fast);
    }

    :deep(.el-upload--picture-card) {
      width: 80px;
      height: 80px;
    }

    .avatar-uploader-icon {
      font-size: 24px;
      color: #8c939d;
      width: 80px;
      height: 80px;
      text-align: center;
    }
  }
}
</style>
